//
//  DetectViewController.m
//  test
//
//  Created by Li Shen on 2021/4/12.
//  Copyright © 2021 lyh. All rights reserved.
//

#import "EcgRealTimeCheckViewController.h"
#import "IKEcgCheckView.h"
#import <IKLibrary/IKLibrary.h>
#import "EcgReportViewController.h"
#import "EcgDeviceScanViewController.h"
#import "EcgCheckOrBindController.h"
#import "IKAudioManager.h"

//找到非绑定设备 容错时间
#define CONNECT_TIME 8

@interface EcgRealTimeCheckViewController ()<IIKEcgDataEvent,IIKEcgCheckEndEvent,IIKEcgStateEvent,IIKEcgDeviceNoWhiteListEvent,IIKEcgDeviceScanEvent>

@property (nonatomic, strong) IKEcgCheckView *ikEcgCheckView;
@property (nonatomic, assign) NSInteger checktime;
//检测过程中不让解绑设备
@property (nonatomic, assign) BOOL isEcgDetecting;
//本次检测是否异常
@property (nonatomic, assign) BOOL isDetectError;
@property (nonatomic, assign) BOOL isBleEnable;
@property (nonatomic, strong) NSString *userInfo;
//是否是第一回合
@property (nonatomic,assign)BOOL isFirstLeg;
@property (nonatomic,assign)NSUInteger firstlegTime;
@property (nonatomic, strong) IKAudioManager *audioManager;

@end

@implementation EcgRealTimeCheckViewController

+(instancetype)getInstance{
    EcgRealTimeCheckViewController *checkVc = [[EcgRealTimeCheckViewController alloc] init];
    return checkVc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"心电检测";
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
//    self.navigationController.navigationBar.translucent = NO;
    self.ikEcgCheckView = [[IKEcgCheckView alloc] init];
    [self.view addSubview:self.ikEcgCheckView];
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 0, 0, 0);
    [self.ikEcgCheckView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(inset);
    }];
    self.checktime = 40;
    self.isEcgDetecting = false;
    self.isBleEnable = true;
    self.audioManager = [[IKAudioManager alloc] init];
    [self.ikEcgCheckView IKSetCheckTime:self.checktime];

    [self setupBindBtn];
    
}


- (void)setupBindBtn{
    UIButton* btn = [[UIButton alloc] initWithFrame:CGRectMake(KScreenW-110, 10, 100, 50)];
    [btn setTitle:@"解绑设备" forState:UIControlStateNormal];
    NSMutableAttributedString* bindString = [[NSMutableAttributedString alloc] initWithString:@"解绑设备"];
    [bindString addAttribute:NSUnderlineStyleAttributeName
                          value:@(NSUnderlineStyleSingle)
                          range:(NSRange){0,[bindString length]}];
 
    [bindString addAttribute:NSForegroundColorAttributeName value:ECG_COLOR_WHITE  range:NSMakeRange(0,[bindString length])];
    [bindString addAttribute:NSUnderlineColorAttributeName value:ECG_COLOR_WHITE range:(NSRange){0,[bindString length]}];
    [btn setAttributedTitle:bindString forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(bindDeviceAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btn];
}

- (void)bindDeviceAction{
    if(self.isEcgDetecting){
        return;
    }
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"解绑设备" message:@"确定要解绑当前设备?" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        
    }];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //Demo绑定在本地
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:@"" forKey:@"key_deviceId"];
        [userDefaults synchronize];

        EcgCheckOrBindController *vc =  (EcgCheckOrBindController*)self.parentViewController;
        [vc showEcgView];
    }];
    
    [alertVc addAction:cancel];
    [alertVc addAction:ok];
    [self presentViewController:alertVc animated:YES completion:nil];
}

- (void)initIKLibrary{
    IKCodeType code = [[IKEcgCheck getInstance] IKInit];
    if (IKCodeTypeFailIKinit == code)
    {
        NSLog(@"IKInit error");
        return;
    }
    
    [[IKEcgCheck getInstance] IKRegistEcgDataEvent:self];
    [[IKEcgCheck getInstance] IKRegistEcgStateEvent:self andUserData:@""];
    [[IKEcgCheck getInstance] IKRegistEcgCheckEndEvent:self andUserData:@""];
    [[IKEcgCheck getInstance] IKRegistEcgDeviceScanEvent:self];
    [[IKEcgCheck getInstance] IKRegistEcgDeviceNoWhiteListEvent:self];
}

- (void)unInitIKLibrary{
    [[IKEcgCheck getInstance] IKUninit];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self initIKLibrary];
    [self startEcgCheck];
    [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self stopEcgCheck];
    [self unInitIKLibrary];
    [[UIApplication sharedApplication] setIdleTimerDisabled: NO];
}

- (void)startEcgCheck{
    self.isDetectError = false;
    self.isEcgDetecting = false;
    self.isFirstLeg = true;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *deviceId =  [userDefaults objectForKey:@"key_deviceId"];
    
    if(![IKPublicUtil isEmpty:deviceId]){
        [[IKEcgCheck getInstance] IKSetEcgDeviceWhiteListDeviceId:deviceId deviceName:@"ikinloop ecg2"];
    }
    NSString *userInfo = @"";
    if([self.delegate respondsToSelector:@selector(createEcgUserInfo:)]){
        userInfo = [self.delegate createEcgUserInfo:self.customData];
    }else{
        NSLog(@"没有实现createEcgUserInfo 方法");
    }
    self.userInfo = userInfo;
    int code = [[IKEcgCheck getInstance] IKStartEcgCheck:userInfo checkTime:(int)self.checktime];
    if(code != 0){
        NSLog(@"IKStartEcgCheck failure---%d",code);
    }
}

- (void)stopEcgCheck{
    [self.ikEcgCheckView IKResetEcgCheckView];
    [[IKEcgCheck getInstance] IKStopEcgCheck];
}
//重置检测状态
- (void)resetEcgCheck{
    [self.ikEcgCheckView IKResetEcgCheckView];
    [self stopEcgCheck];
    [self startEcgCheck];

}

- (void)showBleNoUnauthorizedTip{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"前往设置" message:@"手机蓝牙功能没有权限，请前往设置!" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
       
    }];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:@"App-Prefs:root=Bluetooth"];
        if (@available(iOS 10.0, *)) {
           [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        } else {
           [[UIApplication sharedApplication] openURL:url];
        }
       
    }];
    
    [alertVc addAction:cancel];
    [alertVc addAction:ok];
    [self presentViewController:alertVc animated:YES completion:nil];
}

- (void)showWhetherOrNotToBeBound{
    [self stopEcgCheck];
    [self.audioManager playerFoundNewDev];
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"发现新设备" message:@"若要使用这个设备,请先点击右上角按钮【解绑】原来的设备!" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        [self startEcgCheck];
    }];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self startEcgCheck];
        //Demo绑定在本地
//        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//        [userDefaults setObject:@"" forKey:@"key_deviceId"];
//        [userDefaults synchronize];
//
//        EcgCheckOrBindController *vc =  (EcgCheckOrBindController*)self.parentViewController;
//        [vc showEcgView];
    }];
    
//    [alertVc addAction:cancel];
    [alertVc addAction:ok];
    [self presentViewController:alertVc animated:YES completion:nil];
}

#pragma mark - delegate
-(void)OnReciveEcgData:(int)ecgdata
{
    self.isEcgDetecting = true;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.ikEcgCheckView IKECGDrawData:ecgdata];
    });
}

-(void)OnEcgCheckEnd:(id)userObject
{
    if(self.isDetectError){
        return;
    }
    NSString *ecgSmartResult = [[IKEcgCheck getInstance] IKGetCurrEcgSmartResult];
    NSString *filePath = [[IKEcgCheck getInstance] IKGetCurrEcgDataFilePath];
    NSLog(@"IKGetCurrEcgSmartResult = %@",ecgSmartResult);
    NSLog(@"filePath = %@",filePath);
    __weak typeof(self)weakSelf = self;
    if([self.delegate respondsToSelector:@selector(saveEcgResult:tarFilePath:userInfo:customData:)]){
        [self.delegate saveEcgResult:ecgSmartResult tarFilePath:filePath userInfo:self.userInfo customData:self.customData];
    }else{
        NSLog(@"没有实现saveEcgResult:tarFilePath:userInfo:customData: 方法");
    }
    [self.ikEcgCheckView IKECGSetDetectOver];
    dispatch_async(dispatch_get_main_queue(), ^{
        EcgReportViewController *ecgReportVc = [[EcgReportViewController alloc] init];
        ecgReportVc.tarFilePath = filePath;
        ecgReportVc.ecgSmartResult = ecgSmartResult;
        [weakSelf.navigationController pushViewController:ecgReportVc animated:YES];
    });
}

-(void)OnReciveEcgState:(EcgState)state Desc:(NSString *)desc andUserdata:(id)userdata
{
    NSLog(@"state%ld desc%@ userdata%@", (long)state, desc, userdata);
    if (EcgStateError == state)
    {
        self.isDetectError = true;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self resetEcgCheck];
        });
        
    }else if(EcgStateBLEDisconnect == state){
        [self resetEcgCheck];
    }else if(EcgStateBLENotOpen == state){
        self.isBleEnable = false;
        [self stopEcgCheck];
    }else if(EcgStateBLEOpened == state){
        if(!self.isBleEnable){
            self.isBleEnable = true;
            [self startEcgCheck];
        }
    }else if(EcgStateBLEUnauthorized == state){
        self.isBleEnable = false;
        [self stopEcgCheck];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showBleNoUnauthorizedTip];
        });
       
    }
    [self.ikEcgCheckView IKSetEcgCheckState:state value:userdata];
}

-(void)OnEcgDeviceNoWhiteListEventDeviceId:(NSString *)deviceId
{
    NSLog(@"OnEcgDeviceNoWhiteListEventDeviceId = %@",deviceId);
    if (YES == self.isFirstLeg)
    {
        self.isFirstLeg = NO;
        self.firstlegTime = [NSDate date].timeIntervalSince1970;
        NSLog(@"firstLeg = %lu",(unsigned long)self.firstlegTime);
    }else{
        NSUInteger lastLeg = [NSDate date].timeIntervalSince1970;
        NSLog(@"lastLeg = %lu",(unsigned long)lastLeg);
        if ((lastLeg - self.firstlegTime) <= CONNECT_TIME)
        {
            //do nothing
        }else if((lastLeg - self.firstlegTime) <= 2*CONNECT_TIME){
            [IKPublicUtil runOnMainThread:^{
                [self showWhetherOrNotToBeBound];
            }];
            self.isFirstLeg = YES;
        }else{
            self.isFirstLeg = YES;
        }
    }
}

-(void)OnEcgScanDeviceDataDeviceId:(NSString *)deviceId deviceName:(NSString *)deviceName
{
    NSLog(@"OnEcgScanDeviceDataDeviceId = %@, %@",deviceId,deviceName);
}

@end
